package com.varian.gateway.config;

import com.varian.gateway.filter.GlobalExceptionHandlerFilter;
import com.varian.gateway.filter.GlobalRequestLogFilter;
import com.varian.tool.contant.ResultConstant;
import com.varian.tool.result.IR;
import com.varian.tool.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * @author ben
 * @since 2024/7/19
 */
@Slf4j
@Configuration
public class GatewayConfig {

    @Bean
    public GlobalFilter globalRequestLogFilter() {
        return new GlobalRequestLogFilter();
    }

    @Bean
    public GlobalFilter globalExceptionHandlerFilter(){
        return new GlobalExceptionHandlerFilter();
    }

    public GatewayFilter globalExceptionHandler(ModifyResponseBodyGatewayFilterFactory factory) {
        ModifyResponseBodyGatewayFilterFactory.Config config = new ModifyResponseBodyGatewayFilterFactory.Config();
        config.setRewriteFunction(IR.class, IR.class, (exchange, r) -> {
            log.error("GatewayExceptionHandler: {}", r);
            if (ResultConstant.SERVICE_ERROR.status().equals(r.getStatus()) && ResultConstant.FAIL_CODE.equals(r.getCode())) {
                return Mono.just(R.fail());
            }
            return Mono.just(r);
        });
        return factory.apply(config);
    }
}
